package oauth

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type JWTToken struct {
	UserId    uint64 `json:"user_id"`
	PartnerId uint64 `json:"partner_id"`
	ScopeId   uint64 `json:"scope_id"`
	ExpiresAt int64  `json:"expires_at"`
}

func (j *JWTToken) Valid() error {
	if j.PartnerId != 0 && j.UserId != 0 {
		if j.ExpiresAt >= time.Now().Unix() {
			return nil
		} else {
			return errors.New("jwt token expired")
		}
	}
	return errors.New("user info in jwt is empty")
}

func JWTTokenVerify(secret, tokenStr string) (*JWTToken, error) {
	jwtToken := &JWTToken{}
	var keyFunc jwt.Keyfunc = func(token *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	}
	_, err := jwt.ParseWithClaims(tokenStr, jwtToken, keyFunc)
	if err != nil {
		return nil, err
	}
	return jwtToken, nil
}

func JWTTokenSign(jwtToken *JWTToken, secret string) (tokenStr string, err error) {
	tokenObj := jwt.NewWithClaims(jwt.SigningMethodHS256, jwtToken)
	tokenStr, err = tokenObj.SignedString([]byte(secret))
	if err != nil {
		return "", err
	}
	return tokenStr, nil
}
